import { Component, ViewChild } from '@angular/core';
import { SalePaymentDetailComponent } from '../../sales-master/sales-ledger/sale-payment-detail/sale-payment-detail.component';
import ledgerData from 'src/app/@core/data/mock-purchase-ledger.json';

import { DataTableComponent, DialogService, TableWidthConfig } from '@devui';

// 为采购台账定义本地类型（字段名改为供应商/应付/实付等，更贴近采购语义）
export interface PurchasePayment {
  paymentNum: string;
  paymentDate: string; // ISO string
  isConfirmed: boolean;
  status: string;
  remark: string;
  actualAmount: number; // 此字段沿用 mock 中的 actualAmount，语义对应“实付金额”
}

export interface PurchaseOrderRow {
  purchaseOrderId: number;
  purchaseOrderNum: string;
  orderDate: string; // yyyy-MM-dd HH:mm:ss
  supplierOrderNum?: string;
  supplierName: string;
  supplierShortName: string;
  deliveryDate: string;
  status: string;
  isClosed: boolean;
  creationDate: string;
  creator: string;
  supplierContact?: string;
  contactInfo?: string;
  purchaser?: string;
  department: string;
  settlementCurrency: string; // 人民币
  settlementMethod: string | null;
  remark: string;
  totalQuantity: number;
  totalAmountWithTax: number;
  payments: PurchasePayment[];
  // 运行时附加字段
  display?: boolean;
  payableAmount?: number; // 应付金额（当前用订单含税金额代替）
  paidAmount?: number;    // 计算的：sum(actualAmount)
  unpaidAmount?: number;  // 计算的：totalAmountWithTax - paidAmount
}
@Component({
  selector: 'app-purchase-ledger',
  templateUrl: './purchase-ledger.component.html',
  styleUrls: ['./purchase-ledger.component.scss']
})
export class PurchaseLedgerComponent {
  // 基础数据与筛选
  tableData: PurchaseOrderRow[] = [];
  filteredData: PurchaseOrderRow[] = [];
  pageSizeOptions = [10, 20, 30, 50, 100];
  pager = { total: 0, pageIndex: 1, pageSize: 20 };
  // 查询条件
  orderNo: string = '';
  receiptNo: string = '';
  customerName: string = '';
  rangeDate: Date[] = [];

  @ViewChild(DataTableComponent, { static: true }) datatable!: DataTableComponent;
    constructor(private DialogService:DialogService) { }

  dataTableOptions = {
    columns: [
  { field: 'purchaseOrderNum', header: '单号', fieldType: 'text' },
  { field: 'supplierName', header: '供应商', fieldType: 'text' },
  { field: 'supplierShortName', header: '供应商简称', fieldType: 'text' },
  { field: 'orderDate', header: '下单日期', fieldType: 'text' },
  { field: 'deliveryDate', header: '交货日期', fieldType: 'text' },
  { field: 'totalAmountWithTax', header: '订单金额', fieldType: 'text' },
  { field: 'payableAmount', header: '应付金额', fieldType: 'text' },
  { field: 'paidAmount', header: '实付金额', fieldType: 'text' },
  { field: 'unpaidAmount', header: '未付金额', fieldType: 'text' },
  { field: 'status', header: '状态', fieldType: 'text' },
    ],
  };

  tableWidthConfig: TableWidthConfig[] = [
    { field: '操作', width: '72px' },
    { field: '单号', width: '220px' },
    { field: '供应商', width: '220px' },
    { field: '供应商简称', width: '150px' },
    { field: '下单日期', width: '160px' },
    { field: '交货日期', width: '160px' },
    { field: '订单金额', width: '160px' },
    { field: '应付金额', width: '160px' },
    { field: '实付金额', width: '150px' },
    { field: '未付金额', width: '150px' },
    { field: '状态', width: '120px' },
  ];

  ngOnInit(): void {
    // 初始化：使用采购台账 mock，计算已付/未付金额
    const items = (ledgerData as any).items as PurchaseOrderRow[] | any[];
    this.tableData = items.map((x: any) => {
      // 兼容：若已有采购语义字段则直接使用；否则做一次映射
      const hasPurchaseSchema = !!x.purchaseOrderNum;
      const paid = (x.payments || []).reduce((s: number, p: any) => s + (p.actualAmount || 0), 0);
      const payable = (x.totalAmountWithTax || 0);
      const unpaid = Math.max(payable - paid, 0);
      const row: PurchaseOrderRow = hasPurchaseSchema ? {
        ...x,
        display: false,
        payableAmount: payable,
        paidAmount: paid,
        unpaidAmount: unpaid,
      } : {
        purchaseOrderId: x.saleOrderId,
        purchaseOrderNum: x.saleOrderNum,
        orderDate: x.orderDate,
        supplierOrderNum: x.customerOrderNum,
        supplierName: x.customerName,
        supplierShortName: x.customerShortName,
        deliveryDate: x.deliveryDate,
        status: x.status,
        isClosed: x.isClosed,
        creationDate: x.creationDate,
        creator: x.creator,
        supplierContact: x.customerContact,
        contactInfo: x.contactInfo,
        purchaser: x.salesman,
        department: x.department,
        settlementCurrency: x.settlementCurrency,
        settlementMethod: x.settlementMethod,
        remark: x.remark,
        totalQuantity: x.totalQuantity,
        totalAmountWithTax: x.totalAmountWithTax,
        payments: (x.payments || []).map((p: any) => ({
          paymentNum: p.paymentNum,
          paymentDate: p.paymentDate,
          isConfirmed: p.isConfirmed,
          status: p.status,
          remark: p.remark,
          actualAmount: p.actualAmount,
        })),
        display: false,
        payableAmount: payable,
        paidAmount: paid,
        unpaidAmount: unpaid,
      };
      return row;
    });
    this.applyFilterAndPaging();
  }

  // UI 交互
  toggleRowItem(rowItem: PurchaseOrderRow): void {
    rowItem.display = !rowItem.display;
  }

  // 过滤与分页
  rangeDateChange(event: Date[]) {
    this.rangeDate = event || [];
  }

  search(): void {
    this.pager.pageIndex = 1;
    this.applyFilterAndPaging();
  }

  reset(): void {
    this.orderNo = '';
    this.receiptNo = '';
    this.customerName = '';
    this.rangeDate = [];
    this.pager.pageIndex = 1;
    this.applyFilterAndPaging();
  }

  pageIndexChange(index: number) {
    this.pager.pageIndex = index;
    this.applyFilterAndPaging();
  }

  pageSizeChange(size: number) {
    this.pager.pageSize = size;
    this.pager.pageIndex = 1;
    this.applyFilterAndPaging();
  }

  private applyFilterAndPaging() {
    const all = [...this.tableData];
    // 过滤
    let list = all.filter((o) =>
  (!this.orderNo || o.purchaseOrderNum.includes(this.orderNo)) &&
  (!this.customerName || o.supplierName.includes(this.customerName)) &&
      (!this.receiptNo || (o.payments || []).some((r) => r.paymentNum.includes(this.receiptNo)))
    );

    this.pager.total = list.length;

    // 分页
    const { pageIndex, pageSize } = this.pager;
    const begin = (pageIndex - 1) * pageSize;
    const endIndex = begin + pageSize;
    this.filteredData = list.slice(begin, endIndex);
  }

  // 汇总工具：统计收款单的 actualAmount
  sumPaymentActual(payments: PurchasePayment[]): number {
    return (payments || []).reduce((s, r) => s + (r.actualAmount || 0), 0);
  }

  // 计算到某一笔（含自身）的累计实收
  cumulativeActual(payments: PurchasePayment[], endIndexInclusive: number): number {
    if (!payments || endIndexInclusive == null) return 0;
    const end = Math.min(endIndexInclusive, payments.length - 1);
    let sum = 0;
    for (let i = 0; i <= end; i++) {
      sum += payments[i]?.actualAmount || 0;
    }
    return sum;
  }

  // 计算展开行中，某一笔之后的剩余未收（基于订单应收金额-累计已收）
  remainingAfter(row: PurchaseOrderRow, index: number): number {
    const receivable = row.payableAmount || 0;
    const collected = this.cumulativeActual(row.payments || [], index);
    return Math.max(receivable - collected, 0);
  }

  // 整体汇总：剩余金额（订单应收 - 全部实收）
  groupRemaining(row: PurchaseOrderRow): number {
    const receivable = row.payableAmount || 0;
    const collected = this.sumPaymentActual(row.payments || []);
    return Math.max(receivable - collected, 0);
  }

  // 整体汇总：收款是否完成（未收为 0 即完成）
  groupCompleted(row: PurchaseOrderRow): boolean {
    return (row.unpaidAmount || 0) <= 0;
  }

  private formatDate(d: Date) {
    const y = d.getFullYear();
    const m = (d.getMonth() + 1).toString().padStart(2, '0');
    const day = d.getDate().toString().padStart(2, '0');
    return `${y}-${m}-${day}`;
  }
  detail(payment?: PurchasePayment, order?: PurchaseOrderRow) {
    const results = this.DialogService.open({
      id: 'purchase-payment-detail',
      maxHeight: '70vh',
      width: '960px',
      backdropCloseable: true,
      data: { payment, order },
      title: '采购付款单',
      content: SalePaymentDetailComponent,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '关闭',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }

  // ============ 打印功能（对齐销售台账风格） ============
  private printWithIframe(html: string) {
    const iframe = document.createElement('iframe');
    iframe.style.position = 'fixed';
    iframe.style.right = '0';
    iframe.style.bottom = '0';
    iframe.style.width = '0';
    iframe.style.height = '0';
    iframe.style.border = '0';
    iframe.style.visibility = 'hidden';
    document.body.appendChild(iframe);

    const doc = iframe.contentDocument || iframe.contentWindow?.document;
    if (!doc) {
      document.body.removeChild(iframe);
      return;
    }
    doc.open();
    doc.write(html);
    doc.close();

    setTimeout(() => {
      try {
        iframe.contentWindow?.focus();
        iframe.contentWindow?.print();
      } finally {
        setTimeout(() => {
          if (iframe && iframe.parentNode) {
            iframe.parentNode.removeChild(iframe);
          }
        }, 400);
      }
    }, 200);
  }

  private to2(n: any): string {
    const x = Number(n);
    if (isNaN(x)) return '';
    return x.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  }

  private fmtDateStr(input: any, withTime = false): string {
    if (!input) return '';
    const d = new Date(input);
    if (isNaN(d.getTime())) return String(input);
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const da = String(d.getDate()).padStart(2, '0');
    if (!withTime) return `${y}-${m}-${da}`;
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    return `${y}-${m}-${da} ${hh}:${mm}`;
  }

  // 行内打印：订单行
  printOrderRow(row: PurchaseOrderRow, ev?: Event): void {
    if (ev) { ev.stopPropagation(); ev.preventDefault(); }
    if (!row) return;
  // 改为整单打印：订单信息 + 付款明细
  const html = this.buildPrintHtml(row);
    this.printWithIframe(html);
  }

  // 行内打印：付款行
  printPaymentRow(item: PurchasePayment, order: PurchaseOrderRow, ev?: Event): void {
    if (ev) { ev.stopPropagation(); ev.preventDefault(); }
    if (!item || !order) return;
    const idx = (order.payments || []).indexOf(item);
    const remaining = this.remainingAfter(order, Math.max(idx, 0));
    const html = this.buildPaymentRowHtml(item, order, remaining);
    this.printWithIframe(html);
  }

  // 打印模板：订单行（采购语义）
  private buildOrderRowHtml(order: PurchaseOrderRow): string {
    const to2 = this.to2.bind(this);
    const now = this.fmtDateStr(new Date(), true);
    const style = `
      <style>
        @page { size: A4; margin: 12mm; }
        * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
        .sheet { width: 210mm; min-height: 297mm; margin: 0 auto; }
        .header { display: grid; grid-template-columns: 1fr auto; align-items: center; }
        .title { font-size: 20px; font-weight: 700; }
        .meta { font-size: 12px; color: #555; }
        table { width: 100%; border-collapse: collapse; margin-top: 8px; }
        th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
        th { background: #f5f7fa; }
        tbody tr:nth-child(even) { background: #fafafa; }
        .num { text-align: right; }
      </style>
    `;
    const html = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"/>${style}</head><body>
      <div class="sheet">
        <div class="header">
          <div class="title">采购台账 - 订单行</div>
          <div class="meta">打印时间：${now}</div>
        </div>
        <table>
          <thead>
            <tr>
              <th>单号</th>
              <th>供应商</th>
              <th>供应商简称</th>
              <th>下单日期</th>
              <th>交货日期</th>
              <th class="num">订单金额</th>
              <th class="num">应付金额</th>
              <th class="num">已付金额</th>
              <th class="num">未付金额</th>
              <th>状态</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>${order.purchaseOrderNum || ''}</td>
              <td>${order.supplierName || ''}</td>
              <td>${order.supplierShortName || ''}</td>
              <td>${this.fmtDateStr(order.orderDate, true)}</td>
              <td>${this.fmtDateStr(order.deliveryDate, true)}</td>
              <td class="num">${to2(order.totalAmountWithTax)}</td>
              <td class="num">${to2(order.payableAmount)}</td>
              <td class="num">${to2(order.paidAmount)}</td>
              <td class="num">${to2(order.unpaidAmount)}</td>
              <td>${order.status || ''}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </body></html>`;
    return html;
  }

  // 打印模板：付款行（仅当前行字段）
  private buildPaymentRowHtml(item: PurchasePayment, order: PurchaseOrderRow, remaining: number): string {
    const to2 = this.to2.bind(this);
    const now = this.fmtDateStr(new Date(), true);
    const style = `
      <style>
        @page { size: A4; margin: 12mm; }
        * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
        .sheet { width: 210mm; min-height: 297mm; margin: 0 auto; }
        .header { display: grid; grid-template-columns: 1fr auto; align-items: center; }
        .title { font-size: 20px; font-weight: 700; }
        .meta { font-size: 12px; color: #555; }
        .info { display: grid; grid-template-columns: repeat(2, 1fr); gap: 6px 24px; margin-top: 8px; font-size: 12px; }
        table { width: 100%; border-collapse: collapse; margin-top: 8px; }
        th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
        th { background: #f5f7fa; }
        tbody tr:nth-child(even) { background: #fafafa; }
        .num { text-align: right; }
      </style>
    `;
    const html = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"/>${style}</head><body>
      <div class="sheet">
        <div class="header">
          <div class="title">采购台账 - 付款行</div>
          <div class="meta">打印时间：${now}</div>
        </div>
        <div class="info">
          <div><strong>订单号：</strong>${order.purchaseOrderNum || ''}</div>
          <div><strong>供应商：</strong>${order.supplierName || ''}</div>
          <div><strong>订单金额：</strong>${to2(order.totalAmountWithTax)}</div>
          <div><strong>应付金额：</strong>${to2(order.payableAmount)}</div>
        </div>
        <table>
          <thead>
            <tr>
              <th>付款单号</th>
              <th>付款日期</th>
              <th class="num">本笔实付</th>
              <th class="num">本笔后未付</th>
              <th>状态</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>${item.paymentNum || ''}</td>
              <td>${this.fmtDateStr(item.paymentDate, true)}</td>
              <td class="num">${to2(item.actualAmount)}</td>
              <td class="num">${to2(remaining)}</td>
              <td>${item.isConfirmed ? '已确认' : '未确认'}</td>
              <td>${item.remark || ''}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </body></html>`;
    return html;
  }

  // 保留整单打印模板（订单+付款明细），与销售台账结构一致但字段为采购语义
  private buildPrintHtml(order: PurchaseOrderRow): string {
    const to2 = (n: any) => {
      const x = Number(n);
      if (isNaN(x)) return '';
      return x.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    };
    const now = this.fmtDateStr(new Date(), true);
    const sumActual = this.sumPaymentActual(order.payments || []);
    const count = (order.payments || []).length;
    const remaining = this.groupRemaining(order);

    const rows = (order.payments || []).map((p, i) => `
      <tr>
        <td>${i + 1}</td>
        <td>${p.paymentNum || ''}</td>
        <td>${this.fmtDateStr(p.paymentDate, true)}</td>
        <td class=\"num\">${to2(p.actualAmount)}</td>
        <td>${p.remark || ''}</td>
      </tr>
    `).join('');

    const style = `
      <style>
      @page { size: A4; margin: 10mm; }
      * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
      body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
      .sheet { width: 210mm; min-height: 297mm; padding: 10mm; margin: 0 auto; }
      .header { display: grid; grid-template-columns: 1fr auto; align-items: center; }
      .title { font-size: 22px; font-weight: 700; letter-spacing: 1px; }
      .meta { font-size: 12px; color: #555; }
      .info { display: grid; grid-template-columns: repeat(2, 1fr); gap: 6px 24px; font-size: 12px; margin-top: 6px; }
      table { width: 100%; border-collapse: collapse; margin-top: 10px; }
      th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
      th { background: #f5f7fa; }
      tbody tr:nth-child(even) { background: #fafafa; }
      tr, td, th { page-break-inside: avoid; }
      .num { text-align: right; }
      tfoot td { font-weight: 700; }
      </style>
    `;

    const html = `<!DOCTYPE html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"/>${style}</head><body>
      <div class=\"sheet\">
        <div class=\"header\">
          <div class=\"title\">采购台账</div>
          <div class=\"meta\">打印时间：${now}</div>
        </div>
        <div class=\"info\">
          <div><strong>订单号：</strong>${order.purchaseOrderNum}</div>
          <div><strong>供应商：</strong>${order.supplierName}</div>
          <div><strong>下单日期：</strong>${this.fmtDateStr(order.orderDate, true)}</div>
          <div><strong>交货日期：</strong>${this.fmtDateStr(order.deliveryDate, true)}</div>
          <div><strong>订单金额：</strong>${to2(order.totalAmountWithTax)}</div>
          <div><strong>应付金额：</strong>${to2(order.payableAmount)}</div>
          <div><strong>已付金额：</strong>${to2(order.paidAmount)}</div>
          <div><strong>未付金额：</strong>${to2(order.unpaidAmount)}</div>
        </div>
        <table>
          <thead>
            <tr>
              <th style=\"width:44px;\">序</th>
              <th style=\"width:200px;\">付款单号</th>
              <th style=\"width:200px;\">付款日期</th>
              <th style=\"width:140px;\" class=\"num\">实付金额(元)</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            ${rows || '<tr><td colspan=\"5\" style=\"text-align:center;\">无付款记录</td></tr>'}
          </tbody>
          <tfoot>
            <tr>
              <td colspan=\"2\">合计：${count} 笔</td>
              <td>—</td>
              <td class=\"num\">${to2(sumActual)}</td>
              <td>未付：${to2(remaining)}</td>
            </tr>
          </tfoot>
        </table>
      </div>
    </body></html>`;
    return html;
  }
}
